package com.ecar.api.support.util;

import java.util.HashMap;
import java.util.List;

import com.ecar.core.order.entity.Order;
import com.wilddog.client.DataSnapshot;
import com.wilddog.client.SyncError;
import com.wilddog.client.SyncReference;
import com.wilddog.client.ValueEventListener;
import com.wilddog.client.WilddogSync;
import com.wilddog.wilddogcore.WilddogApp;
import com.wilddog.wilddogcore.WilddogOptions;

public class WilddogUtil {
	
	//初始化司机的野狗线程
	public static SyncReference getDriverRef(String url){
		String driver=Props.getValue("wilddog.passenger");
		return getInstance(driver, "driver", url);
	}
	//初始化乘客的野狗线程
	public static SyncReference getPassengerRef(String url){
		String passenger=Props.getValue("wilddog.passenger");
		return getInstance(passenger, "passenger",url);
	}
	
	//初始化野狗的线程
	private static SyncReference getInstance(String appId,String refName,String url){
		WilddogOptions driverOptions = new WilddogOptions.Builder().setSyncUrl("https://"+appId+".wilddogio.com").build();
		SyncReference ref = WilddogSync.getInstance(WilddogApp.initializeApp(driverOptions,refName)).getReference(url);

		try {
			Thread.sleep(1);
		} catch (InterruptedException e) {
			e.printStackTrace();
		}
		return ref;
	}
	
	//写入实时单
	public static void sendNowOrderToDriver(String driverId,HashMap<String, Object> map){
		getDriverRef("WilddogLocation/order").child(driverId).child("/now").updateChildren(map);
	}
	//写入拼车单
	public static void sendCarpoolOrderToDriver(String driverId,HashMap<String, Object> map){
		sendNowOrderToDriver(driverId, map);
	}
	//写入预约单
	public static void sendAppointmentOrderToDriver(String driverId,HashMap<String, Object> map){
		getDriverRef("WilddogLocation/order").child(driverId).child("/appointment").updateChildren(map);
	}
	//写入预约单排序
	public static void sendSortDriver(final List<Order> list,final String driverId,final HashMap<String, Object> map){
			getDriverRef("WilddogLocation/order").child(driverId).child("/now").addListenerForSingleValueEvent(new ValueEventListener() {
				@Override
				public void onDataChange(DataSnapshot dataSnapshot) {
					for(Order carpool:list){
						if(dataSnapshot.hasChild(carpool.getOrderNum())){
							getDriverRef("WilddogLocation/order").child(driverId).child("/now").child(carpool.getOrderNum()).updateChildren(map);
						}
					}
				}
				@Override
				public void onCancelled(SyncError arg0) {
				}
			});
	}
	
	//写入数据
	public static void sendOrderToPassenger(String orderNum,HashMap<String, Object> map){
		getPassengerRef("WilddogLocation/order").child(orderNum).updateChildren(map);
	}
	
	public static void removePassengerOrder(String orderNum){
		getPassengerRef("WilddogLocation/order").child(orderNum).removeValue();
	}
	
	public static void removeDriverOrder(String driverId){
		getDriverRef("WilddogLocation/order").child(driverId).removeValue();
	}
}
